package com.walterweimod.auxiliary_attributes.event;

import com.walterweimod.auxiliary_attributes.attribute.ModAttributes;
import com.walterweimod.auxiliary_attributes.mobeffect.ModMobEffects;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import java.util.Objects;

import static com.walterweimod.auxiliary_attributes.Auxiliary_attributes.getLogger;
import static com.walterweimod.auxiliary_attributes.util.ModAttributeUtils.addAttributeModifier;
import static com.walterweimod.auxiliary_attributes.util.ModAttributeUtils.removeAttributeModifier;
import static com.walterweimod.auxiliary_attributes.util.ModUtils.getLivingEntityHealthPercent;
import static com.walterweimod.auxiliary_attributes.util.ModUtils.hyphenName;
import static com.walterweimod.auxiliary_attributes.mobeffect.Endurance.*;

@Mod.EventBusSubscriber
public class EnduranceEvent {
    @SubscribeEvent
    public static void onLivingBeingHurt(LivingHurtEvent event){
        LivingEntity livingEntity = event.getEntityLiving();
        MobEffectInstance endurance = livingEntity.getEffect(ModMobEffects.ENDURANCE.get());

        if (Objects.nonNull(endurance)){
            int amplifier = endurance.getAmplifier();
            float healthPercent = getLivingEntityHealthPercent(livingEntity);

            if (healthPercent <= Math.min(50.0F + amplifier, 85.0F)){
                modifyAttributes(livingEntity, amplifier);
                event.setAmount(event.getAmount() * Math.max(0.85F - 0.01F * amplifier, 0.2F));
            }
        }
    }

    private static void modifyAttributes(LivingEntity livingEntity, int amplifier){
        if (Objects.nonNull(livingEntity)){
            AttributeInstance heal_bonus = livingEntity.getAttribute(ModAttributes.HEAL_BONUS.get());

            if (Objects.nonNull(heal_bonus)){
                removeAttributeModifier(
                        livingEntity,
                        heal_bonus.getAttribute(),
                        getEnduranceHealBonusUUID()
                );

                addAttributeModifier(
                        livingEntity,
                        heal_bonus.getAttribute(),
                        0.5D + 0.3D * amplifier,
                        getEnduranceHealBonusUUID(),
                        AttributeModifier.Operation.ADDITION,
                        false
                );

                getLogger().info(hyphenName("Endurance Heal Bonus", 15));
                getLogger().info("放射性衰变总治疗量提升：{}", heal_bonus.getValue());
            }
        }
    }
}
